package com.pang.songbo.songboexcel.util;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Excel写入工具类
 * 支持.xls和.xlsx格式
 */
public class ExcelWriter {
    
    /**
     * 创建Excel工作簿
     * @param isXlsx 是否为xlsx格式
     * @return Workbook对象
     */
    public static Workbook createWorkbook(boolean isXlsx) {
        return isXlsx ? new XSSFWorkbook() : new HSSFWorkbook();
    }
    
    /**
     * 写入数据到Excel文件
     * @param filePath 文件路径
     * @param sheetName 工作表名称
     * @param headers 表头数组
     * @param data 数据列表
     * @throws IOException
     */
    public static void writeExcel(String filePath, String sheetName, 
                                   String[] headers, List<Object[]> data) throws IOException {
        boolean isXlsx = filePath.endsWith(".xlsx");
        Workbook workbook = createWorkbook(isXlsx);
        FileOutputStream fos = null;
        
        try {
            Sheet sheet = workbook.createSheet(sheetName);
            
            // 创建表头样式
            CellStyle headerStyle = createHeaderStyle(workbook);
            
            // 写入表头
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
                // 设置列宽
                sheet.setColumnWidth(i, 15 * 256);
            }
            
            // 写入数据
            CellStyle dataStyle = createDataStyle(workbook);
            for (int i = 0; i < data.size(); i++) {
                Row row = sheet.createRow(i + 1);
                Object[] rowData = data.get(i);
                
                for (int j = 0; j < rowData.length; j++) {
                    Cell cell = row.createCell(j);
                    setCellValue(cell, rowData[j]);
                    cell.setCellStyle(dataStyle);
                }
            }
            
            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            
            fos = new FileOutputStream(filePath);
            workbook.write(fos);
            
        } finally {
            if (workbook != null) {
                workbook.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }
    
    /**
     * 写入Map数据到Excel文件
     * @param filePath 文件路径
     * @param sheetName 工作表名称
     * @param data 数据列表（Map格式）
     * @throws IOException
     */
    public static void writeExcelWithMap(String filePath, String sheetName, 
                                         List<Map<String, Object>> data) throws IOException {
        if (data == null || data.isEmpty()) {
            return;
        }
        
        // 从第一个数据中提取表头
        Map<String, Object> firstRow = data.get(0);
        String[] headers = firstRow.keySet().toArray(new String[0]);
        
        // 转换为Object数组格式
        List<Object[]> dataList = new java.util.ArrayList<>();
        for (Map<String, Object> row : data) {
            Object[] rowArray = new Object[headers.length];
            for (int i = 0; i < headers.length; i++) {
                rowArray[i] = row.get(headers[i]);
            }
            dataList.add(rowArray);
        }
        
        writeExcel(filePath, sheetName, headers, dataList);
    }
    
    /**
     * 创建表头样式
     * @param workbook 工作簿
     * @return 单元格样式
     */
    private static CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        
        // 设置背景色
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        
        // 设置边框
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        
        // 设置字体
        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 12);
        style.setFont(font);
        
        // 设置居中对齐
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        
        return style;
    }
    
    /**
     * 创建数据样式
     * @param workbook 工作簿
     * @return 单元格样式
     */
    private static CellStyle createDataStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        
        // 设置边框
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        
        // 设置垂直居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        
        return style;
    }
    
    /**
     * 设置单元格值
     * @param cell 单元格
     * @param value 值
     */
    private static void setCellValue(Cell cell, Object value) {
        if (value == null) {
            cell.setCellValue("");
        } else if (value instanceof String) {
            cell.setCellValue((String) value);
        } else if (value instanceof Integer) {
            cell.setCellValue((Integer) value);
        } else if (value instanceof Double) {
            cell.setCellValue((Double) value);
        } else if (value instanceof Boolean) {
            cell.setCellValue((Boolean) value);
        } else if (value instanceof java.util.Date) {
            cell.setCellValue((java.util.Date) value);
        } else {
            cell.setCellValue(value.toString());
        }
    }
    
    /**
     * 创建带日期的数据样式
     * @param workbook 工作簿
     * @return 单元格样式
     */
    public static CellStyle createDateStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        
        // 创建日期格式
        CreationHelper createHelper = workbook.getCreationHelper();
        style.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd"));
        
        return style;
    }
    
    /**
     * 合并单元格
     * @param sheet 工作表
     * @param firstRow 起始行
     * @param lastRow 结束行
     * @param firstCol 起始列
     * @param lastCol 结束列
     */
    public static void mergeCells(Sheet sheet, int firstRow, int lastRow, 
                                    int firstCol, int lastCol) {
        sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
    }
    
    /**
     * 测试方法
     */
    public static void main(String[] args) {
        try {
            // 测试数据
            String[] headers = {"序号", "姓名", "年龄", "部门", "入职日期"};
            List<Object[]> data = new java.util.ArrayList<>();
            data.add(new Object[]{1, "张三", 28, "技术部", new java.util.Date()});
            data.add(new Object[]{2, "李四", 32, "市场部", new java.util.Date()});
            data.add(new Object[]{3, "王五", 25, "人事部", new java.util.Date()});
            
            // 写入Excel文件
            writeExcel("员工信息.xlsx", "员工表", headers, data);
            System.out.println("Excel文件生成成功！");
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
